package controller;

import com.root.health.bean.CorrelationInfo;
import com.root.health.bean.UserInfo;
import com.root.health.service.CorrelationService;
import com.root.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Controller
public class CorrelationController {
    @Autowired
    CorrelationService correlationService;
    @Autowired
    UserService userService;
    /**
     *
     * 添加用户关联信息
     */
    @GetMapping(value = "correlation")
    public String correlationPage(){

        return "correlation";
    }
    @PostMapping("correlation")
    public String correlationPage(UserInfo userInfo, CorrelationInfo correlationInfo, HttpSession session, Model model, HttpServletRequest request){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }
        UserInfo tempo_user = (UserInfo) session.getAttribute("loginUser");
        userInfo = userService.getUserbyName(tempo_user.getUserName());
        //由于Session传递来的用户是前端页面中输入的用户实体类，没有被数据库增加userid，所以需要再从数据库查询一次当前用户获取userid
        String correlationUserName = request.getParameter("correlationUsername");//从前端获取关联用户名
        UserInfo correlationUser = userService.getUserbyName(correlationUserName);//根据该用户名获取用户实体
        //测试用System.out.println("loginuser = "+userInfo);
        if(correlationUser == null){
            model.addAttribute("msgforcorr","该用户名不存在，请重新输入");
            //判断该用户是否存在，不存在则返回关联用户页面
            return "correlation";
        }
        long parentid = 0;
        long childrenid = 0;
        if(userInfo.getRole().equals("parents")&&correlationUser.getRole().equals("children")){
            parentid = userInfo.getUserId();
            childrenid = correlationUser.getUserId();
            for (int i = 0; i < correlationService.childrenidgetByid(parentid).toArray().length; i++) {
                if(correlationService.childrenidgetByid(parentid).get(i).getChildrenid() == childrenid){
                    model.addAttribute("msgforcorr","该用户已与您关联");
                    return "correlation";
                }
            }//判断当前用户是否被添加至关联信息表中
            //测试用System.out.println("1.parentid = "+parentid+" childrenid = "+childrenid);
            //如果当前用户角色为父母且关联用户为子女，则将该角色id放入parentid中，输入的关联用户放入childrenid中
        }else if (userInfo.getRole().equals("children")&&correlationUser.getRole().equals("parents")){
            childrenid = userInfo.getUserId();
            parentid = correlationUser.getUserId();
            for (int i = 0; i < correlationService.parentidgetByid(childrenid).toArray().length; i++) {
                if(correlationService.parentidgetByid(childrenid).get(i).getParentid() == parentid){
                    model.addAttribute("msgforcorr","该用户已与您关联");
                    return "correlation";
                }
            }//判断当前用户是否被添加至关联信息表中
            //测试用System.out.println("2.parentid = "+parentid+" childrenid = "+childrenid);
            //否则如果当前用户角色为子女且关联用户为父母，则将该角色id放入childrenid中，输入的关联用户放入parentid中
        }else{
            model.addAttribute("msgforcorr","您关联的用户与您的角色相同（都为父母/子女）");
            return "correlation";//如果用户角色都不符合，抛出异常
        }
        //测试用System.out.println("3.parentid = "+parentid+" childrenid = "+childrenid);
        correlationService.correlationInfo(parentid,childrenid);
            model.addAttribute("successHref","selectcorrinfo");
            return "success";
//        if(userInfo.getRole().equals("parent")){
//            return "healthinfo";
//        }else{
//            return "main";
//        }//如果当前用户角色为父母，则跳转到输入基本健康信息页面（可以给一个选择提示）
    }
    /**
     *
     * 查询用户关联信息
     */
    @GetMapping("selectcorrinfo")
    public String selectcorrinfo(CorrelationInfo correlationInfo, UserInfo userInfo, Model model, HttpSession session) {
        if (session.getAttribute("loginUser") == null) {
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg", "请重新登录");
            //回到登录页面
            return "login";
        }
        UserInfo tempo_user = (UserInfo) session.getAttribute("loginUser");
        userInfo = userService.getUserbyName(tempo_user.getUserName());
        //由于Session传递来的用户是前端页面中输入的用户实体类，没有被数据库增加userid，所以需要再从数据库查询一次当前用户获取userid
        List<UserInfo> List_corruser = new LinkedList<UserInfo>();
        List<Map<String,Object>> corrMapList = new LinkedList<>();
        Map<String,Object> corrMap;
        if(userInfo.getRole().equals("parents")){//根据当前用户角色查询对应userid
            List<CorrelationInfo> List_corr = correlationService.childrenidgetByid(userInfo.getUserId());
            for (int i = 0; i < List_corr.toArray().length; i++) {
                int finalI = i;
                UserInfo a_user = userService.getUserbyId(List_corr.get(i).getChildrenid());
                corrMap = new HashMap<>(){{
                    put("id",List_corr.get(finalI).getId());
                    put("username",a_user.getUserName());
                    put("realname",a_user.getRealname());
                    put("role","子女");
                }};
                //将查询出的id放入getUserbyId查询对应user信息，并将user信息放入List中准备遍历给前端
                corrMapList.add(corrMap);
            }
            model.addAttribute("corrMapList",corrMapList);
            return "selectcorr";
        }else{
            corrMapList = ChildrenCorrUser(userInfo);//子女角色查询关联父母账户
            model.addAttribute("corrMapList",corrMapList);
            return "selectcorr";
        }
    }
    /**
     *
     * 子女角色查询关联父母账户
     */
    public List<Map<String,Object>> ChildrenCorrUser(UserInfo userInfo){
        List<Map<String,Object>> userMapList = new LinkedList<>();
        Map<String,Object> userMap;
        List<CorrelationInfo> List_corr = correlationService.parentidgetByid(userInfo.getUserId());
        for (int i = 0; i < List_corr.toArray().length; i++) {
            int finalI = i;
            UserInfo parent_user = userService.getUserbyId(List_corr.get(i).getParentid());
            userMap = new HashMap<>(){{
                put("id",List_corr.get(finalI).getId());
                put("parentId",List_corr.get(finalI).getParentid());
                put("username",parent_user.getUserName());
                put("realname",parent_user.getRealname());
                put("userid",parent_user.getUserId());
                put("role","父母");
            }};
            //将查询出的id放入getUserbyId查询对应user信息，并将user信息放入List中准备遍历给前端
            userMapList.add(userMap);
        }
        return userMapList;
    }
    /**
     *
     * 从关联用户查询页面携带参数实现删除操作
     */

    @PostMapping("corrDel")
    public String corrDel(){

        return "selectcorr";
    }

    @GetMapping("corrDel")
    public String corrDel(long corrid,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        session.setAttribute("corrid",corrid);
        correlationService.corrDel(corrid);
            model.addAttribute("successHref","selectcorrinfo");
            return "success";
    }
}
